package utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import entry.PrintElementType;
import entry.PrintElements;
import entry.options.*;
import enums.PrintElementTypeEnums;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @Author LS
 * @Date 2023/4/16 22:19
 * @Description 针对Panel的printElements字段json进行序列化
 **/

public class PrintElementsListJsonDeserializer implements ObjectDeserializer {

    public List<PrintElements> deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
        List<PrintElements> result = new ArrayList<>();
        JSONArray jsonArray = parser.parseObject(JSONArray.class);
        Iterator<Object> iterator =  jsonArray.iterator();
        while (iterator.hasNext()){
            PrintElements printElements = new PrintElements();
            Options options = null;
            JSONObject jsonObject = (JSONObject) iterator.next();
            // 打印类型，根据打印类型生成不同的options类
            PrintElementType printElementType = jsonObject.getObject("printElementType", PrintElementType.class);
            if (printElementType.getType().equals(PrintElementTypeEnums.TEXT)){
                options = jsonObject.getObject("options", TextOptions.class);
            }else if (printElementType.getType().equals(PrintElementTypeEnums.LONGTEXT)){
                options = jsonObject.getObject("options", LongTextOptions.class);
            }else if (printElementType.getType().equals(PrintElementTypeEnums.TABLECUSTOM)){
                options = jsonObject.getObject("options", TableOptions.class);
            }else if (printElementType.getType().equals(PrintElementTypeEnums.IMAGE)){
                options = jsonObject.getObject("options", ImageOptions.class);
            }else if (
                    printElementType.getType().equals(PrintElementTypeEnums.HLINE)
                            || printElementType.getType().equals(PrintElementTypeEnums.VLINE)
                            || printElementType.getType().equals(PrintElementTypeEnums.HTML)
                            || printElementType.getType().equals(PrintElementTypeEnums.RECT)
                            || printElementType.getType().equals(PrintElementTypeEnums.OVAL)
            ) {
                options = jsonObject.getObject("options", GraphicalOptions.class);
            }else {
                options = jsonObject.getObject("options", Options.class);
            }
            // 构建返回值
            printElements.setOptions(options);
            printElements.setPrintElementType(printElementType);
            result.add(printElements);
        }
        return result;
    }

    public int getFastMatchToken() {
        return 0;
    }
}
